package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 设备Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-14
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备集合
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);

        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("同步产品列表失败!");
        }

        //存入redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    @Override
    public List<ProductVo> allProduct() {
        String productsStr = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);

        if (StringUtils.isEmpty(productsStr)) {
            return Collections.emptyList();
        }

        return JSONUtil.toList(productsStr, ProductVo.class);
    }

    @Override
    public void register(DeviceDto deviceDto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(queryWrapper) > 0) {
            throw new BaseException("设备名称重复!");
        }

        //判断设备标识码是否重复
        LambdaQueryWrapper<Device> nodeIdWrapper = new LambdaQueryWrapper<>();
        nodeIdWrapper.eq(Device::getNodeId, deviceDto.getNodeId());
        if (count(nodeIdWrapper) > 0) {
            throw new BaseException("设备标识码重复!");
        }

        //判断同一位置是否绑定同一类产品
        LambdaQueryWrapper<Device> condition = new LambdaQueryWrapper<>();
        condition.eq(Device::getBindingLocation, deviceDto.getBindingLocation()).eq(Device::getLocationType, deviceDto.getLocationType()).eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType()).eq(Device::getProductKey, deviceDto.getProductKey());

        if (count(condition) > 0) {
            throw new BaseException("同一位置只能绑定同一类产品!");
        }


        //新增设备iot mysql
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();

        body.setNodeId(deviceDto.getNodeId());
        body.setDeviceName(deviceDto.getDeviceName());
        body.setProductId(deviceDto.getProductKey());

        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);

        request.withBody(body);
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
            System.out.println(response.toString());
        } catch (ConnectionException e) {
            throw new BaseException("设备注册失败!");
        }

        //写入数据库
        Device device = BeanUtil.copyProperties(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        try {
            save(device);
        } catch (Exception e) {
            throw new BaseException("该老人/位置已经绑定产品,请重新选择");
        }
    }

    @Override
    public DeviceDetailVo getDetail(String iotId) {
        //查询数据库
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);

        Device device = getOne(queryWrapper);

        if (ObjectUtil.isEmpty(device)) {
            return null;
        }

        //查询华为云
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);

        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (ConnectionException e) {
            throw new BaseException("查询设备详情失败!");
        }

        //组装数据
        DeviceDetailVo deviceDetailVo = BeanUtil.copyProperties(device, DeviceDetailVo.class);

        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();

        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);

            //转换时区
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();

            deviceDetailVo.setActiveTime(activeTime);
        }

        return deviceDetailVo;
    }


    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //查询华为云
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);

        ShowDeviceShadowResponse response;
        try {
            response = client.showDeviceShadow(request);
        } catch (ConnectionException e) {
            throw new BaseException("查询设备上报数据失败!");
        }

        List<DeviceShadowData> shadow = response.getShadow();
        if (ObjectUtil.isEmpty(shadow)) {
            return Collections.emptyList();
        }

        Object properties = shadow.get(0).getReported().getProperties();

        JSONObject jsonObject = JSONUtil.parseObj(properties);

        //组装数据
        List<Map<String, Object>> list = new ArrayList<>();

        //时区转换
        String eventTimeStr = shadow.get(0).getReported().getEventTime();
        LocalDateTime time = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");

        LocalDateTime eventTime = time.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();

            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);

            list.add(map);
        });

        return list;

    }

    @Override
    public void updateDevice(DeviceDto deviceDto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(queryWrapper) > 0) {
            throw new BaseException("设备名称重复!");
        }

        //判断同一位置是否绑定同一类产品
        LambdaQueryWrapper<Device> condition = new LambdaQueryWrapper<>();
        condition.eq(Device::getBindingLocation, deviceDto.getBindingLocation()).eq(Device::getLocationType, deviceDto.getLocationType()).eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType()).eq(Device::getProductKey, deviceDto.getProductKey());

        if (count(condition) > 0) {
            throw new BaseException("同一位置只能绑定同一类产品!");
        }

        //修改设备
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        UpdateDevice body = new UpdateDevice();


        body.setDeviceName(deviceDto.getDeviceName());
        body.setDescription(deviceDto.getDeviceDescription());

        AuthInfoWithoutSecret authInfoWithoutSecret = new AuthInfoWithoutSecret();
        authInfoWithoutSecret.setSecureAccess(true);
        body.setAuthInfo(authInfoWithoutSecret);

        request.withBody(body);
        request.withDeviceId(deviceDto.getIotId());
        UpdateDeviceResponse response;
        try {
            response = client.updateDevice(request);
            System.out.println(response.toString());
        } catch (ConnectionException e) {
            throw new BaseException("修改设备失败!");
        }

        //写入数据库
        Device device = BeanUtil.copyProperties(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        try {
            updateById(device);
        } catch (Exception e) {
            throw new BaseException("该老人/位置已经绑定产品,请重新选择");
        }
    }

    @Override
    public void deleteDevice(String iotId) {
        //调用华为云
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        try {
            DeleteDeviceResponse response = client.deleteDevice(request);
        } catch (ConnectionException e) {
            throw new BaseException("删除设备失败!");
        }

        //删除数据库
        deviceMapper.deleteByIotId(iotId);
    }
}
